<template>
  <div class="releaseExam">
    <div v-if="$store.state.teacherInfomation">
      <el-form
        :model="ruleFormrelease"
        status-icon
        :rules="ruleselease"
        ref="ruleFormrelease"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="考试名称" prop="name">
          <el-input
            type="text"
            v-model="ruleFormrelease.name"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="请选择专业" prop="major">
          <el-select
            placeholder="请选择专业"
            v-model="ruleFormrelease.major"
            style="width: 100%"
          >
            <el-option label="请选择专业" value=""> </el-option>
            <el-option
              :label="item.major"
              :value="item.major"
              v-for="(item, index) in selectMajor"
              :key="index"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择班级" prop="classroom">
          <el-select
            placeholder="请选择班级"
            v-model="ruleFormrelease.classroom"
            style="width: 100%"
          >
            <el-option label="请选择班级" value=""> </el-option>
            <el-option
              :label="item.classroom"
              :value="item.classroom"
              v-for="(item, index) in selectclassroom"
              :key="index"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="试卷编号" prop="eid">
          <el-select
            placeholder="请选择试卷编号"
            v-model="ruleFormrelease.eid"
            style="width: 100%"
          >
            <el-option label="请选择试卷编号" value=""> </el-option>
            <el-option
              v-for="(item, index) in arr2"
              :label="`${item}已发布`"
              :value="item"
              :key="index"
              disabled
            >
            </el-option>
            <!-- 避免key值一样加个标识符 -->
            <el-option
              v-for="(item2, index2) in arr3"
              :label="item2"
              :value="item2"
              :key="`${index2}+arr3`"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="开始时间" prop="start_time">
          <el-input
            type="datetime-local"
            v-model="ruleFormrelease.start_time"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="结束时间" prop="end_time">
          <el-input
            type="datetime-local"
            v-model="ruleFormrelease.end_time"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleFormrelease')"
            >提交</el-button
          >
          <el-button @click="resetForm('ruleFormrelease')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-else>请前往个人中心完善信息 <router-link to="/teacherHome/teacherHomepage">点击前往</router-link> </div>
  </div>
</template>
<script>
import axios from "axios";
import { Message, MessageBox } from "element-ui";
import qs from "qs";
export default {
  mounted() {
    this.getMajor(); //获取专业
  },
  watch: {
    "ruleFormrelease.major": {
      deep: true,
      handler(val, oldval) {
        //获取班级
        this.getClassroom(val);
      },
    },
    "ruleFormrelease.classroom": {
      deep: true,
      handler(val, oldval) {
        console.log(val);
        //获取班级对应发布的试卷
        this.getEid(); //获取试卷id ,要动态获取，不能放到mounted因为mounted只加载一次
        this.getAlreadyEid(val);
      },
    },
  },
  methods: {
    //提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submitAxios();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    submitAxios() {
      axios({
        method: "post",
        url: "v1/teachers/examinfo",
        data: qs.stringify({
          testname: this.ruleFormrelease.name,
          major: this.ruleFormrelease.major,
          classroom: this.ruleFormrelease.classroom,
          selecteid: this.ruleFormrelease.eid,
          starttime: this.ruleFormrelease.start_time,
          endtime: this.ruleFormrelease.end_time,
        }),
        headers: {
          "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        },
      })
        .then((result) => {
          if (result.data.status == 200) {
            Message.success({
              showClose: true,
              message: "提交成功",
              type: "success",
            });
            this.$router.push("/teacherHome");
          } else {
            Message.error({
              showClose: true,
              message: "提交失败",
              type: "error",
            });
          }
        })
        .catch((err) => {
          MessageBox("服务器开小差了~请稍后再试", "提示", {
            confirmButtonText: "确定",
            type: "error",
          });
          console.log(err);
        });
    },

    //去重
    repeat(arr, arr2) {
      for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr2.length; j++) {
          if (arr[i] == arr2[j]) {
            arr.splice(i, 1);
          }
        }
        // this.arr3 = arr;
      }
      return arr;
      // console.log(this.arr3);
    },
    //获取专业
    getMajor() {
      axios
        .get(`/v1/teachers/getmajor`)
        .then((res) => {
          // console.log(res.data);
          this.selectMajor = res.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //获取班级
    getClassroom(val) {
      axios
        .get(`/v1/teachers/selectclassroom/${val}`)
        .then((res) => {
          // console.log(res.data);
          this.selectclassroom = res.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //获取试卷id
    getEid() {
      axios
        .get("/v1/teachers/examsearch")
        .then((res) => {
          // console.log(res.data);
          this.eid = res.data.data;
          this.arr = []; //每次获取到新的数据时把arr置为空,不然去重splice剩余的值会一直push
          for (let i = 0; i < this.eid.length; i++) {
            this.arr.push(this.eid[i].eid);
          }
          // console.log(this.arr)
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //获取班级对应已发布的试卷id
    getAlreadyEid(val) {
      axios
        .get(`/v1/teachers/classeid/${val}`)
        .then((res) => {
          if (res.data.status == 200) {
            // console.log(res.data);
            this.alreadyEid = res.data.data;
            //把拿到的eid存入数组
            for (let i = 0; i < this.alreadyEid.length; i++) {
              this.arr2.push(this.alreadyEid[i].eid);
            }
            // console.log(this.arr2)
            //去重
            this.arr3 = this.repeat(this.arr, this.arr2);
          } else {
            //如果没拿到数据
            this.arr2 = [];
            this.arr3 = this.repeat(this.arr, this.arr2);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
  data() {
    var validateName = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("考试名称不能为空"));
      } else {
        callback();
      }
    };
    var validateClassroom = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择班级"));
      } else {
        callback();
      }
    };
    var validateMajor = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择院系"));
      } else {
        callback();
      }
    };
    var validateEid = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择试卷编号"));
      } else {
        callback();
      }
    };
    var validateStartTime = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择开始时间"));
      } else {
        callback();
      }
    };
    var validateEndTime = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择结束时间"));
      } else {
        callback();
      }
    };
    return {
      selectclassroom: [""], //班级，给初始值，避免axios异步没有取得数据时报错
      selectMajor: [""],
      eid: [""], //试卷编号对象
      alreadyEid: [""], //已发布的试卷编号对象
      arr: [], //试卷编号
      arr2: [], //已发布的试卷编号
      arr3: [], //去重后的试卷编号，也就是未发布的
      ruleFormrelease: {
        name: "",
        major: "",
        classroom: "",
        eid: "",
        start_time: "",
        end_time: "",
      },
      ruleselease: {
        name: [{ validator: validateName, trigger: "blur" }],
        classroom: [{ validator: validateMajor, trigger: "change" }],
        major: [{ validator: validateClassroom, trigger: "change" }],
        eid: [{ validator: validateEid, trigger: "change" }],
        start_time: [{ validator: validateStartTime, trigger: "blur" }],
        end_time: [{ validator: validateEndTime, trigger: "blur" }],
      },
    };
  },
};
</script>
<style lang="scss">
.releaseExam {
  margin: 0 auto;
  margin-top: 50px;
}
</style>